// exercises.js
import { reactive, ref } from 'vue';
import { exerciseDeleteService, getAllExercise, exerciseSearchService, exercisesAddService, exerciseUpdateService } from "../utils/exercises.js";
import { nextTick } from 'vue';
import { Logger } from 'sass';
import { all } from 'axios';


export const exercises = {
    currentPage: ref(1),
    pageSize: ref(5),
    size: ref("default"),
    background: ref(false),
    disabled: ref(false),
    dialogFormVisible: ref(false),
    //分页数据
    total: ref(0), // 总条目数
    allexercises: ref([]), // 全部用户数据
    exercisesList: ref([]), //当前页数据
    formInline: reactive({
        name: '',
    }),
    form: reactive({
        ExerciseID: '',
        ExerciseName: '',
        Description: '',
        Category: '',
        status: '',
        //获取所有用户
    }),


    handleSizeChange(val) {
        exercises.pageSize.value = val;
        exercises.updateList(); // 更新当前页数据
        console.log(`${val} items per page`);
    },

    handleCurrentChange(val) {
        exercises.currentPage.value = val;
        exercises.updateList(); // 更新当前页数据
        console.log(`current page: ${val}`);
    },
    restest() {
        exercises.formInline.name = ''
        exercises.total.value = 0;

        exercises.getAllExercisee();
    },

    async handleDelete(id) {
        const confirmed = confirm("确定要删除此用户吗？"); // 确认删除
        if (confirmed) {
            const result = await exerciseDeleteService(id); // 传递实际的用户 ID

            console.log("用户已删除");
            if (confirmed) {
                const result = await exerciseDeleteService(id);
                exercises.exerciseSearch();
            } else {
                alert("取消删除");

            }

        }

    },


    async exerciseSearch() {
        try {
            let data = await exerciseSearchService(exercises.formInline.name);

            if (Array.isArray(data) && data.length > 0) {
                exercises.allexercises.value = data; // 不需要深拷贝
                exercises.total.value = data.length; // 更新总条目数
            } else {
                console.warn("No data returned or data is not in array format:", data);
                exercises.allexercises.value = [];
                exercises.total.value = 0;
            }

            exercises.updateList();



        } catch (error) {
            console.error("Error fetching exercises:", error);
        }
    },
    async getAllExercisee() {
        try {
            const data = await getAllExercise(); // 获取数据
            // 更新总条目数

            exercises.allexercises.value = data;
            exercises.total.value = data.length;

            // 调用分页更新方法
            exercises.updateList();
        } catch (error) {
            console.error("Error fetching exercises:", error);
        }
    },

    statusa: "",
    updateList() {
        const start = (this.currentPage.value - 1) * this.pageSize.value;
        const end = start + this.pageSize.value;

        // 设置分页数据
        this.exercisesList.value = this.allexercises.value.slice(start, end);

        // 更新每项数据的状态
        exercises.exercisesList.value.forEach(exercise => {
            if (exercise && exercise.hasOwnProperty("status")) {
                // 将状态 1 显示为 "成功"，状态 0 显示为 "失败"
                exercise.statusText = exercise.status === 1 ? "正常" : "保修";
            } else {
                console.error("Exercise has no status");
            }
        });
    }

    ,

    async Submitform() {
        console.log("提交表单数据:", exercises.form);
        try {
            await exercisesAddService(exercises.form);
            console.log("表单提交成功:");
            exercises.getAllExercisee();
            exercises.dialogFormVisible.value = false; // 关闭对话框
        } catch (error) {
            ElMessage.error("注册失败");
            dialogFormVisible.value = false;
            throw err;
        }
    },

    dishandle: ref(false),

    async handleEdit(id, currentStatus) {
        try {
            // 反转状态：如果当前是 1（成功），改为 0（失败）；如果是 0（失败），改为 1（成功）
            const newStatus = currentStatus === 1 ? 0 : 1;

            // 创建更新对象，传递新的状态
            const update = { status: newStatus };

            // 调用更新服务，更新数据
            await exerciseUpdateService(id, update);

            console.log("更新 ID:", id, "新状态:", newStatus === 1 ? "成功" : "失败");

            // 重新获取数据，确保最新的状态
            exercises.getAllExercisee();
        } catch (error) {
            console.error("更新数据失败", error);
            alert("获取数据失败");
        }
    }





};









//获取表单里的所有数据
